// FileUploadController.java
package org.example.rubbish.controller;

import lombok.RequiredArgsConstructor;
import org.example.rubbish.result.Result;
import org.example.rubbish.service.COSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/admin/upload")
@RequiredArgsConstructor
public class FileUploadController {
    @Autowired
    private  COSService cosService;

    /**
     * 上传文件到COS
     */
    @PostMapping
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只支持图片文件");
            }

            // 验证文件大小 (最大5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("文件大小不能超过5MB");
            }

            // 上传到COS
            String fileUrl = cosService.uploadFile(file);

            return Result.success(fileUrl);

        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误: " + e.getMessage());
        }
    }

    /**
     * 删除COS文件
     */
    @DeleteMapping
    public Result<Void> deleteFile(@RequestParam String fileUrl) {
        try {
            cosService.deleteFile(fileUrl);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件删除失败: " + e.getMessage());
        }
    }
}